package cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


@WebServlet(name = "cookieTest")
    public class CookieTest extends HttpServlet {
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

            resp.setContentType("text/html;charset=utf-8");
//获取
            Cookie[] cookies = req.getCookies();
            boolean flag = false;
        if (cookies !=null && cookies.length >0){
            for (Cookie cookie : cookies){
                String name = cookie.getName();
                if ("LastTime".equals(name)){
                    flag = true;
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年mm月dd日 HH:mm:ss");
                    String str_date = sdf.format(date);
                    cookie.setValue(str_date);
                    cookie.setMaxAge(60*60*24*30);
                    resp.addCookie(cookie);



                    String value = cookie.getValue();
                    resp.getWriter().write("<h1>欢迎回来，您上次访问的时间为："+value+"</h1>");

                    break;
                }
            }
        }
        if (cookies == null || cookies.length==0 ||flag==false){
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年mm月dd日 HH:mm:ss");
            String str_date = sdf.format(date);
            Cookie cookie = new Cookie("lastTime",str_date);

           //设置cookie的存活时间
            cookie.setMaxAge(60*60*24*30);//一个月
            resp.addCookie(cookie);
            resp.getWriter().write("<h1>欢迎您首次访问！</h1>");

        }
        }

        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            this.doPost(req, resp);
        }
    }
